/*
 *    This file is part of BlobDB.
 *
 *    BlobDB is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    BlobDB is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with BlobDB.  If not, see <http://www.gnu.org/licenses/>.
 *    
 *    Copyright(c) 2011 Michael Kankkonen
 *    http://www.vnetcon.org
 */


package org.vnetcon.blobdb.database.util;

import java.util.Arrays;

public class InfoBase {

	public InfoBase(){
	}

	public int writeInt(byte[] data, int iCursor, int intvalue) throws Exception {
		byte ib[] = intToBytes(intvalue);
		int i = 0;
		while(i < ib.length){
			data[iCursor] = ib[i];
			i++;
			iCursor++;
		}
		return ib.length;
	}

	public void writeBytes(byte[] data, int iCursor, byte[] bytes) throws Exception {
		byte ib[] = bytes;
		int i = 0;
		while(i < ib.length){
			data[iCursor] = ib[i];
			i++;
			iCursor++;
		}
	}

	public synchronized static byte[] readBytes(byte[] data, int iCursor, int iSize) throws Exception {
//		byte bret[] = new byte[iSize];
//		int i = 0;
		byte bret[] = Arrays.copyOfRange(data, iCursor, iCursor + iSize);
		/*
		while(i < iSize){
			bret[i] = data[iCursor + i];
			i++;
		}
		*/
		return bret;
	}
	
	public byte[] intToBytes(int intValue){
		int number = intValue;
		byte [] intByte = new byte [4];
		for (int i = 0; i < 4; i++)
		{
			intByte[i] = (byte)(number >> (8 * i));
		}
		return intByte;
	}

	public static synchronized int bytesToInt(byte[] intByte) {
		int fromByte = 0;
		for (int i = 0; i < 4; i++) {
			int n = (intByte[i] < 0 ? (int) intByte[i] + 256 : (int) intByte[i]) << (8 * i);
			fromByte += n;
		}
		return fromByte;
	}	

	public static synchronized int readInt(byte[] data, int iCursor){
		byte b[] = new byte[4];
		int i = 0;
		while(i < b.length){
			b[i] = data[iCursor];
			iCursor++;
			i++;
		}
		return bytesToInt(b);
	}
	
	
}
